<script setup lang="ts">
import { computed, onMounted, reactive } from 'vue';
import { $t } from '@/locales';
import { useFormRules, useNaiveForm } from '@/hooks/common/form';
import { useAuthStore } from '@/store/modules/auth';
import { sha256 } from '@/utils/crypto';
import { getImgCode } from '@/service/api';

defineOptions({
  name: 'PwdLogin'
});

const authStore = useAuthStore();
const { formRef, validate } = useNaiveForm();

interface FormModel {
  userName: string;
  password: string;
  imgCode: string;
  imgText: string;
  imgToken: string;
}

const model: FormModel = reactive({
  userName: 'admin',
  password: 'admin123',
  imgCode: '',
  imgText: '',
  imgToken: ''
});

const rules = computed<Record<keyof FormModel, App.Global.FormRule[]>>(() => {
  // inside computed to make locale reactive, if not apply i18n, you can define it without computed
  const { formRules } = useFormRules();

  return {
    userName: formRules.userName,
    password: formRules.pwd,
    imgCode: formRules.imgCode
  };
});

async function handleSubmit() {
  await validate();
  // await authStore.login(model.userName, sha256(model.password));
  const loginSuccess = await authStore.login(model.userName, model.password, model.imgCode, model.imgToken);
  if (!loginSuccess) {
    model.imgCode = '';
    fetchImgCode();
  }
}

async function fetchImgCode() {
  const { error, data } = await getImgCode();
  if (!error && data) {
    model.imgText = `data:image/gif;base64,${data.imgText}`;
    model.imgToken = data.imgToken;
  }
}

onMounted(() => {
  fetchImgCode();
});
</script>

<template>
  <NForm ref="formRef" :model="model" :rules="rules" size="large" :show-label="false" @keyup.enter="handleSubmit">
    <NFormItem path="userName">
      <NInput v-model:value="model.userName" size="medium" :placeholder="$t('page.login.common.userNamePlaceholder')" />
    </NFormItem>
    <NFormItem path="password">
      <NInput
        v-model:value="model.password"
        size="medium"
        type="password"
        show-password-on="click"
        :placeholder="$t('page.login.common.passwordPlaceholder')"
      />
    </NFormItem>
    <NFormItem path="imgCode">
      <NInput v-model:value="model.imgCode" size="medium" :placeholder="$t('page.login.common.imgCodePlaceholder')" />
      <NImage style="cursor:pointer;margin-left: 20px" preview-disabled :src="model.imgText" @click="fetchImgCode" />
    </NFormItem>
    <NSpace vertical :size="24">
      <NButton type="primary" size="large" block :loading="authStore.loginLoading" @click="handleSubmit">
        {{ $t('common.confirm') }}
      </NButton>
    </NSpace>
  </NForm>
</template>

<style scoped></style>
